import redis
import threading
import os
import sys
import logging
import logging.handlers

class Listener(threading.Thread):
   def __init__(self, r, channels,log):
     threading.Thread.__init__(self)
     self.redis = r
     self.pubsub = self.redis.pubsub()
     self.pubsub.subscribe(channels)
     self.log=log
   def work(self, item):
       self.log.info(item['data'])
     #self.devRedis.publish('Rcs'+chr(1)+'WorkHint'+chr(1)+'QDR',item['data'])
       print item['data']
   def run(self):
     for item in self.pubsub.listen():
       if item['data'] == "KILL":
         self.pubsub.unsubscribe()
         print self, "unsubscribed and finished"
         break
       else:
         self.work(item)
 
if __name__ == "__main__":
    log = logging.getLogger()
    log.setLevel(logging.DEBUG)
    h1 = logging.handlers.RotatingFileHandler('redis.log',maxBytes=2097152,backupCount=5)
    h1.setLevel(logging.INFO)
    f=logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    h1.setFormatter(f)
    log.addHandler(h1)
    normalRedis = redis.Redis(host='192.168.91.17', port=6379, db=0)
    print 'connect redis OK!'
    log.info('connect redis OK!')
    #devRedis = redis.Redis(host='192.168.0.94', port=6379, db=0)
    client = Listener(normalRedis, ['Rcs'+chr(1)+'WorkHint'+chr(1)+'QDR'],log)
    client.start()
